// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
    env: 'zbdc-6gavbhj633c62e27'
})
const db = cloud.database()


exports.main = async (event, context) => {
    const wxContext = cloud.getWXContext() // 不用再传openid
    //根据接收的m,n值，查询数据
    if (event.type == 'cet4') {
        let res = await db.collection('CET4').skip(event.m).limit(event.n).get()
        return res.data
    } else if (event.type == 'cet6') {
        let wordList = []
        let res = await db.collection('CET6')
            .field({
                headWord: true,
                content: true,
                _id: true
            })
            .skip(event.m)
            .limit(event.n)
            .get()
        new Promise(() => {
            res.data.forEach(item => {
                // 拼接samples
                let sms = item.content.word.content.sentence ? item.content.word.content.sentence.sentences ? item.content.word.content.sentence.sentences : [] : []
                sms = sms.map((itm, index) => {
                    return itm.sCn.concat('\n' + itm.sContent) // 拼接
                }).join('\n')
                // 拼接phrase
                let phr = item.content.word.content.phrase ? item.content.word.content.phrase.phrases ? item.content.word.content.phrase.phrases : [] : []
                phr = phr.slice(0, 3).map((itm, idx) => {
                    return itm.pCn.concat('\n' + itm.pContent + ';')
                }).join('\n')
                // definition
                let def = item.content.word.content.trans
                def = def.map((itm, idx) => {
                    return itm.pos.concat('.' + itm.tranCn)
                }).join('\n')
                console.log(def)
                wordList.push({
                    _id: item._id,
                    content: item.headWord,
                    type: 'cet6',
                    pron: item.content.word.content.phone || item.content.word.content.usphone,
                    definition: def, // 要拼
                    samples: sms, // 要拼
                    phrase: phr, // 要拼
                    lyric: item.lyric ? item.lyric : '',
                    address: item.address ? item.address : ''
                })
            })
        })
        return wordList
    } else if (event.type == 'kaoyan') {
        let wordList = []
        let res = await db.collection('KAOYAN')
            .field({
                headWord: true,
                content: true,
                _id: true
            })
            .skip(event.m)
            .limit(event.n)
            .get()
        new Promise(() => {
            res.data.forEach(item => {
                // 拼接samples
                let sms = item.content.word.content.sentence ? item.content.word.content.sentence.sentences ? item.content.word.content.sentence.sentences : [] : []
                sms = sms.map((itm, index) => {
                    return itm.sCn.concat('\n' + itm.sContent) // 拼接
                }).join('\n')
                // 拼接phrase
                let phr = item.content.word.content.phrase ? item.content.word.content.phrase.phrases ? item.content.word.content.phrase.phrases : [] : []
                phr = phr.slice(0, 3).map((itm, idx) => {
                    return itm.pCn.concat('\n' + itm.pContent + ';')
                }).join('\n')
                // definition
                let def = item.content.word.content.trans
                def = def.map((itm, idx) => {
                    return itm.pos.concat('.' + itm.tranCn)
                }).join('\n')
                console.log(def)
                wordList.push({
                    _id: item._id,
                    content: item.headWord,
                    type: 'kaoyan',
                    pron: item.content.word.content.phone || item.content.word.content.usphone,
                    definition: def, // 要拼
                    samples: sms, // 要拼
                    phrase: phr, // 要拼
                    lyric: item.lyric ? item.lyric : '',
                    address: item.address ? item.address : ''
                })
            })
        })
        return wordList
    } else if (event.type == 'statusWord') { // 用户上传音频状态
        let successSet = [],
        checkSet = [],
        failSet = [];
        let {
            data
        } = await db.collection('userUpfile')
            .where({
                content: event.content,
                _id: event.id,
                openid: event.openid
            })
            .get()
        console.log(data)
        new Promise(() =>{ // 根据状态将数据分为三种
            data.forEach(item =>{
                if (item.status == "success"){
                    successSet.push(item)
                }else if(item.status == "checking"){
                    checkSet.push(item)
                }else if(item.status == "fail"){
                    failSet.push(item)
                }
            })
        })
        return {
            success:successSet, 
            check:checkSet, 
            fail:failSet
        }
    } else if (event.type == 'getBooksList') { // 返回所有书籍和每本的单词数量
        let res = await db.collection('books').get()
        for (let i = 0; i < res.data.length; i++) {
            if (res.data[i].type == 'cet4') {
                let count = await db.collection('CET4').count()
                res.data[i].total = count.total
            } else if (res.data[i].type == 'cet6') {
                let count = await db.collection('CET6').count()
                res.data[i].total = count.total
            } else if (res.data[i].type == 'kaoyan') {
                let count = await db.collection('KAOYAN').count()
                res.data[i].total = count.total
            }
        }
        return res
    } else if (event.type == 'amnCheck') { // 审核页面
        let {
            data
        } = await db.collection('userUpfile')
            .get()
        return data
    } else if (event.type == 'checkerID') { // 判断用户身份
        let {
            data
        } = await db.collection('userData')
            .where({
                openid: wxContext.OPENID
            })
            .field({
                auth: true
            })
            .get()
        console.log(data, wxContext.OPENID)
        return data
    } else if (event.type == 'noteBook') { // 生词本
        let {
            data
        } = await db.collection('userData')
            .where({
                openid: wxContext.OPENID
            })
            .field({
                noteBook: true
            })
            .limit(1000)
            .get()
        return data
    } else if (event.type == "starData") { // 收藏本
        console.log(event)
        let {
            data
        } = await db.collection('userData')
            .where({
                // _openid:"oJrSP5NLfVIjvaryup8EOEBDMnZ0"
                openid: wxContext.OPENID
            })
            .field({
                starData: true
            })
            .limit(1000)
            .get()
        return data
    } else if (event.type == "audioStatus"){ // 查询审核库里是否含有此单词
        let {
            data
        } = await db.collection('userUpfile')
            .where({
                content: event.content,
                _id: event.id,
                openid: wxContext.openid
            })
            .get()
        console.log(data)
        return data
    } else if (event.type == "isNewUser"){ // 判断用户表里是否有此用户
        let {data} = await db.collection('userID')
        .where({
            openid:event.openid
        })
        .get()
        console.log('data:',data)
        return data
    } else if (event.type == "isOldUser"){ // 老用户的话获取数据
        let res = db.collection('userData').where({
            openid: event.openid
        }).get()
        console.log(res)
        return res
    }
}